<template>
  <div>
    <!-- 使用 js 进行数组的合并 -->
    <h1>使用 js 进行数组的合并</h1>
    <p>现在有数组a，b，a = [1, 2, 3] b = [3, 4, 5]</p>
    <el-button type="primary" size="default" @click="arrayMerge()">合并数组</el-button>
    <p>第一种：{{ c1 }}</p>
    <p>第二种：{{ c2 }}</p>
    <p>第三种：{{ c3 }}</p>
    <p>第四种：{{ c4 }}</p>

    <el-button type="primary" size="default" @click="readJson('/json/test.json')">读取本地json文件内容
    </el-button>
    <el-button type="primary" size="default" @click="openCamera">打开摄像头</el-button>
    <el-button type="primary" size="default" @click="openCameraShow">打开摄像头并显示画面</el-button>
    <el-button type="primary" size="default" @click="connectDB">连接数据库</el-button>

  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      c1: [],
      c2: [],
      c3: [],
      c4: []
    }
  },
  methods: {
    arrayMerge() {
      let a = [1, 2, 3];
      let b = [3, 4, 5];
      //现有a，b两个数组，怎么进行合并
      //第一种：直接使用
      a.forEach(item => {
        this.c1.push(item)
      })
      b.forEach(item => {
        this.c1.push(item)
      })
      console.log("第一种数组合并的方法：", this.c1);

      //第二种：JavaScript的Array对象中提供了一个concat()方法，作用是连接两个或更多的数组，并返回一个新的数组。
      //要注意的是，concat()方法不会改变原数组，而是返回一个新的数组。这样，当我们需要进行多次数组合并的时候，就会造成内存浪费。
      this.c2 = a.concat(b);
      console.log("第二种数组合并的方法：", this.c2);

      //第三种
      //函数的apply方法有一个特性，那就是func.apply(obj,argv)，argv是一个数组。所以我们可以利用这点。arr1.push.apply(arr1, arr2);
      //调用arr1.push这个函数实例的apply()方法，同时把arr1、arr2当作参数传入，这样arr1.push这个方法就会遍历arr1和arr2数组的所有元素，达到合并的效果。
      //简单理解就是，上面这段代码可以看做是：arr1.push(4, 5, 6);
      a.push.apply(a, b);
      this.c3 = a;
      console.log("第三种数组合并的方法：", this.c3);
      //上面三种方法在常规使用上其实并没有区别，只是要另外注意两个小问题：
      //1.以上3种合并方法在举例的时候并没有考虑过两个原数组谁的长度更小，好的做法是预先判断两个原数组哪个更大，
      //然后使用大数组合并小数组，这样就能减少了数组元素操作的次数，提高了代码的执行效率。
      //2.有时候我们既不希望原数组（arr1、arr2）改变，又不想手动新增一个变量，这时就只能使用concat()方法了。

      //最后，我感觉还有一种也可以
      this.c4 = [...a, ...b]
      console.log("第四种数组合并的方法：", this.c4);

      //计算两个日期之间相差的天数
      // var date1 = new Date("2018-01-01");
      // var date2 = new Date("2018-01-02");
      // var days = Math.floor((date2.getTime() - date1.getTime()) / (24 * 3600 * 1000));
      // console.log(days);

    },
    //计算两个日期之间相差的天数
    getDays(date1, date2) {
      var date1 = new Date(date1);
      var date2 = new Date(date2);
      var days = Math.floor((date2.getTime() - date1.getTime()) / (24 * 3600 * 1000));
      return days;
    },
    //每个月的天数
    getDaysInMonth(year, month) {
      return new Date(year, month, 0).getDate();
    },
    //每个月第一天是星期几
    getFirstDayOfMonth(year, month) {
      return new Date(year, month - 1, 1).getDay();
    },
    //每个月第一天是几号
    getFirstDayOfMonth2(year, month) {
      return new Date(year, month - 1, 1).getDate();
    },
    //把list转化为tree
    listToTree(list, id, pid) {
      var map = {};
      var roots = [];
      for (var i = 0; i < list.length; i++) {
        map[list[i][id]] = list[i];
      }
      for (var i = 0; i < list.length; i++) {
        var node = list[i];
        if (node[pid] == 0) {
          roots.push(node);
        } else {
          map[node[pid]]['children'] = map[node[pid]]['children'] || [];
          map[node[pid]]['children'].push(node);
        }
      }
      return roots;
    },

    //修改计算机系统时间
    setSystemTime(time) {
      var date = new Date(time);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hour = date.getHours();
      var minute = date.getMinutes();
      var second = date.getSeconds();
      var time = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
      return time;
    },

    //根据手机号码获取归属地
    getAddress(phone) {
      var address = "";
      var url = "http://apis.juhe.cn/mobile/get?phone=" + phone + "&key=d8f8f8f8f8f8f8f8f8f8f8f8f8f8f8";
      $.ajax({
        url: url,
        type: "get",
        dataType: "jsonp",
        success: function (data) {
          if (data.resultcode == 200) {
            address = data.result.province + data.result.city;
          }
        }
      });
      return address;
    },


    //使用this.$axios分页查询
    getPageList(url, params, callback) {
      this.$axios.get(url, {
        params: params
      }).then(res => {
        callback(res.data);
      })
    },

    //手机号的正则表达式
    checkPhone(phone) {
      var reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
      if (reg.test(phone)) {
        return true;
      } else {
        return false;
      }
    },

    //ip地址的正则表达式
    checkIp(ip) {
      var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
      if (reg.test(ip)) {
        return true;
      } else {
        return false;
      }
    },


    //删除数组中重复的元素
    delRepeat(arr) {
      var newArr = [];
      for (var i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) == -1) {
          newArr.push(arr[i]);
        }
      }
      return newArr;
    },

    //递归删除文件的方法
    delFile(path) {
      var files = [];
      if (fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach(function (file, index) {
          var curPath = path + "/" + file;
          if (fs.statSync(curPath).isDirectory()) { // recurse
            this.delFile(curPath);
          } else { // delete file
            fs.unlinkSync(curPath);
          }
        });
        fs.rmdirSync(path);
      }
    },


    //上传文件
    uploadFile(file, callback) {
      var formData = new FormData();
      formData.append('file', file);
      this.$axios.post('/api/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        callback(res.data);
      })
    },

    //下载文件
    downloadFile(url, callback) {
      this.$axios.get(url, {
        responseType: 'blob'
      }).then(res => {
        callback(res.data);
      })
    },

    //读取本地json文件内容
    readJson(path) {
      //fs需要自己安装
      var data = fs.readFileSync(path, 'utf-8');
      console.log(data);
      return JSON.parse(data);
    },

    //使用XMLHttpRequest读取本地json文件内容
    readJson2(path) {
      var xhr = new XMLHttpRequest();
      xhr.open('GET', path, false);
      xhr.send(null);
      if (xhr.status == 200) {
        return JSON.parse(xhr.responseText);
      }
    },

    //图片转化base64
    imgToBase64(url, callback) {
      var img = new Image();
      img.src = url;
      img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var ext = url.substring(url.lastIndexOf(".") + 1).toLowerCase();
        var dataURL = canvas.toDataURL("image/" + ext);
        callback(dataURL);
      };
    },

    //base64转化图片
    base64ToImg(base64, callback) {
      var img = new Image();
      img.src = base64;
      img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var dataURL = canvas.toDataURL("image/png");
        callback(dataURL);
      };
    },

    //图片背景透明
    imgTransparent(url, callback) {
      var img = new Image();
      img.src = url;
      img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var dataURL = canvas.toDataURL("image/png");
        callback(dataURL);
      };
    },

    //图片缩放
    imgScale(url, width, height, callback) {
      var img = new Image();
      img.src = url;
      img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);
        var dataURL = canvas.toDataURL("image/png");
        callback(dataURL);
      };
    },

    //图片裁剪
    imgCrop(url, x, y, width, height, callback) {
      var img = new Image();
      img.src = url;
      img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, x, y, width, height, 0, 0, width, height);
        var dataURL = canvas.toDataURL("image/png");
        callback(dataURL);
      };
    },

    //图片旋转
    imgRotate(url, angle, callback) {
      var img = new Image();
      img.src = url;
      img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.translate(img.width / 2, img.height / 2);
        ctx.rotate(angle * Math.PI / 180);
        ctx.drawImage(img, -img.width / 2, -img.height / 2);
        var dataURL = canvas.toDataURL("image/png");
        callback(dataURL);
      };
    },

    //图片灰度
    imgGray(url, callback) {
      var img = new Image();
      img.src = url;
      img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        var imgData = ctx.getImageData(0, 0, img.width, img.height);
        var pixes = imgData.data;
        for (var i = 0, j = pixes.length; i < j; i += 4) {
          var pix = (pixes[i] + pixes[i + 1] + pixes[i + 2]) / 3;
          pixes[i] = pix; //r
          pixes[i + 1] = pix; //g
          pixes[i + 2] = pix; //b
        }
        ctx.putImageData(imgData, 0, 0);
        var dataURL = canvas.toDataURL("image/png");
        callback(dataURL);
      };
    },

    //图片颜色反转
    imgInvert(url, callback) {
      var img = new Image();
      img.src = url;
      img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        var imgData = ctx.getImageData(0, 0, img.width, img.height);
        var pixes = imgData.data;
        for (var i = 0, j = pixes.length; i < j; i += 4) {
          pixes[i] = 255 - pixes[i]; //r
          pixes[i + 1] = 255 - pixes[i + 1]; //g
          pixes[i + 2] = 255 - pixes[i + 2]; //b
        }
        ctx.putImageData(imgData, 0, 0);
        var dataURL = canvas.toDataURL("image/png");
        callback(dataURL);
      };
    },

    //优化图片
    imgOptimize(url, callback) {
      var img = new Image();
      img.src = url;
      img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        var imgData = ctx.getImageData(0, 0, img.width, img.height);
        var pixes = imgData.data;
        for (var i = 0, j = pixes.length; i < j; i += 4) {
          var r = pixes[i];
          var g = pixes[i + 1];
          var b = pixes[i + 2];
          var gray = (r + g + b) / 3;
          pixes[i] = gray; //r
          pixes[i + 1] = gray; //g
          pixes[i + 2] = gray; //b
        }
        ctx.putImageData(imgData, 0, 0);
        var dataURL = canvas.toDataURL("image/png");
        callback(dataURL);
      };
    },

    //图片上传回显
    imgUpload(url, callback) {
      var img = new Image();
      img.src = url;
      img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL("image/png");
        callback(dataURL);
      };
    },


    //打开摄像头
    openCamera(callback) {
      var video = document.createElement("video");
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      var localMediaStream = null;
      var videoObj = {
        "video": true,
        "audio": false
      };
      if (navigator.getUserMedia) {
        navigator.getUserMedia(videoObj, function (stream) {
          video.src = window.URL.createObjectURL(stream);
          localMediaStream = stream;
          video.play();
          callback(video, canvas, ctx, localMediaStream);
        }, function (error) {
          console.log("访问用户媒体设备失败：" + error.name, error);
        });
      } else if (navigator.webkitGetUserMedia) {
        navigator.webkitGetUserMedia(videoObj, function (stream) {
          video.src = window.webkitURL.createObjectURL(stream);
          localMediaStream = stream;
          video.play();
          callback(video, canvas, ctx, localMediaStream);
        }, function (error) {
          console.log("访问用户媒体设备失败：" + error.name, error);
        });
      } else if (navigator.mozGetUserMedia) {
        navigator.mozGetUserMedia(videoObj, function (stream) {
          video.src = window.URL.createObjectURL(stream);
          localMediaStream = stream;
          video.play();
          callback(video, canvas, ctx, localMediaStream);
        }, function (error) {
          console.log("访问用户媒体设备失败：" + error.name, error);
        });
      }
    },

    //打开摄像头并显示画面
    openCameraShow(callback) {
      var video = document.createElement("video");
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      var localMediaStream = null;
      var videoObj = {
        "video": true,
        "audio": false
      };
      if (navigator.getUserMedia) {
        navigator.getUserMedia(videoObj, function (stream) {
          video.src = window.URL.createObjectURL(stream);
          localMediaStream = stream;
          video.play();
          callback(video, canvas, ctx, localMediaStream);
        }, function (error) {
          console.log("访问用户媒体设备失败：" + error.name, error);
        });
      } else if (navigator.webkitGetUserMedia) {
        navigator.webkitGetUserMedia(videoObj, function (stream) {
          video.src = window.webkitURL.createObjectURL(stream);
          localMediaStream = stream;
          video.play();
          callback(video, canvas, ctx, localMediaStream);
        }, function (error) {
          console.log("访问用户媒体设备失败：" + error.name, error);
        });
      } else if (navigator.mozGetUserMedia) {
        navigator.mozGetUserMedia(videoObj, function (stream) {
          video.src = window.URL.createObjectURL(stream);
          localMediaStream = stream;
          video.play();
          callback(video, canvas, ctx, localMediaStream);
        }, function (error) {
          console.log("访问用户媒体设备失败：" + error.name, error);
        });
      }
    },

    /**
   * @description: 图片压缩
   */
    compressImg(file) {
      let disposeFile = file;
      if (Object.prototype.toString.call(file) === '[object Blob]') {
        disposeFile = new File([file], file.name, { type: file.type });
      }
      const read = new FileReader(),
        _that = this;
      const fileSize = parseFloat(parseInt(disposeFile['size']) / 1024 / 1024).toFixed(2);
      // 小于1m不压缩
      if (fileSize < 1) return file;
      read.readAsDataURL(disposeFile);
      return new Promise((resolve, reject) => {
        try {
          read.onload = (e) => {
            const img = new Image();
            img.src = e.target.result;
            img.onload = function () {
              let w = Math.floor(this.width / 2),
                h = Math.floor(this.height / 2);
              const canvas = document.createElement('canvas');
              const ctx = canvas.getContext('2d');
              let base64;
              canvas.setAttribute('width', w);
              canvas.setAttribute('height', h);
              ctx.drawImage(this, 0, 0, w, h);
              console.log(w, h);
              if (fileSize < 1) {
                // 如果图片小于一兆 那么不执行压缩操作
                base64 = canvas.toDataURL(disposeFile['type'], 1);
              } else if (fileSize > 1 && fileSize < 2) {
                // 如果图片大于1M并且小于2M 那么压缩0.5
                base64 = canvas.toDataURL(disposeFile['type'], 0.5);
              } else {
                // 如果图片超过2m 那么压缩0.2
                base64 = canvas.toDataURL(disposeFile['type'], 0.2);
              }
              resolve(_that.dataURLtoFile(base64, disposeFile.name));
            };
          };
        } catch (error) {
          reject(disposeFile);
        }
      });
    },
    /**
     * @description: 将base64编码转回file文件
     */
    dataURLtoFile(dataurl, fileName) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], fileName, {
        type: mime,
      });
    },













  },
}
</script>

<style scoped>
</style>